package com.study.config;

import com.study.pojo.Configuration;
import com.study.pojo.MappedStatement;
import com.study.pojo.SqlType;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

import java.io.InputStream;
import java.util.List;

public class XMLMapperBuilder {
    private Configuration configuration;

    public XMLMapperBuilder(Configuration configuration) {
        this.configuration = configuration;
    }

    /**
     * 解析mapper.xml，并放入configuration中
     *
     * @param inputStream
     * @throws DocumentException
     */
    public void parse(InputStream inputStream) throws DocumentException {
        Document document = new SAXReader().read(inputStream);
        Element rootElement = document.getRootElement();

        String namespace = rootElement.attributeValue("namespace");


        constructMappedStatement(rootElement.selectNodes("//select"), namespace, SqlType.SELECT);
        constructMappedStatement(rootElement.selectNodes("//update"), namespace, SqlType.UPDATE);
        constructMappedStatement(rootElement.selectNodes("//insert"), namespace, SqlType.INSERT);
        constructMappedStatement(rootElement.selectNodes("//delete"), namespace, SqlType.DELETE);
    }

    private void constructMappedStatement(List<Element> selectNodes, String namespace, SqlType sqlType) {
        if (selectNodes == null || selectNodes.isEmpty()) {
            return;
        }
        for (Element selectNode : selectNodes) {
            String id = selectNode.attributeValue("id");
            String resultType = selectNode.attributeValue("resultType");
            String parameterType = selectNode.attributeValue("parameterType");
            String sqlText = selectNode.getTextTrim();

            MappedStatement mappedStatement = MappedStatement.builder()
                    .id(id)
                    .resultType(resultType)
                    .parameterType(parameterType)
                    .sql(sqlText)
                    .sqlType(sqlType)
                    .build();

            configuration.getMappedStatementMap().put(namespace + "." + id, mappedStatement);
        }
    }
}
